import React, { useEffect, useRef, useState } from 'react';
import PriceSpreadCharts from '../PriceSpreadCharts';
import PowerPrediction from '../PowerPrediction';
import _ from 'lodash';
import styles from './index.less';
import {
  Button,
  Divider,
  Form,
  message,
  Modal,
  Popconfirm,
  Select,
  Space,
  Spin,
  Switch,
} from 'antd';
import { ApartmentOutlined, CaretDownOutlined } from '@ant-design/icons';
import TjTable from '@/pages/ETrade/components/TjTable';
import { buildContinuousTimePoint, getColumns } from './helper';
import { TIME_96 } from '../../../components/helper.js';
import { arrToFormData, formDataToArr } from '@/utils/editorTable';
import { smoothOptions } from '../../helper';
import LogModal from '../LogModal/index.jsx';
import { connect } from 'umi';
import StrategyCitationModal from '../StrategyCitationModal';
import { TjChart } from '@/pages/ETrade/components';
import { TRDefault } from '#/components';
import { havePermissions } from '@/pages/ETrade/ShorttermForecastingRedesign/tool';

const StepOneContent = (props) => {
  const {
    searchForm = {},
    smoothStatus,
    store,
    dispatch,
    quoteStationId,
    dataList,
    dataSourceList,
    openAi,
    menuCode,
    dataListLoading,
    aiAdjustmentLoading,
    saveType,
    aiAdjustmentChartData,
    saveButtonDisabled,
    buttonPermissions,
    defaultDataSourceId,
    defaultCapacity,
  } = props;
  const [form] = Form.useForm();

  const [logVisible, setLogVisible] = useState(false);

  const timrArr = useRef(TIME_96);

  const query = (params) => {
    dispatch({
      type: 'shortTermForecastingRedesignV2/getQueryRateData',
      payload: params,
    });
  };

  const setDataList = (arr = []) => {
    dispatch({
      type: 'shortTermForecastingRedesignV2/setState',
      payload: {
        dataList: arr,
      },
    });
  };

  useEffect(() => {
    setTableData(dataList);
  }, [dataList]);

  const queryNewStrategy = (obj) => {
    const arr = formDataToArr(obj, dataList, 'id');
    dispatch({
      type: 'shortTermForecastingRedesignV2/getAiAdjustmentChartData',
      payload: {
        dataList: arr,
        stationId: searchForm.stationId,
        store: store,
        smoothStatus: smoothStatus,
        quoteStationId: quoteStationId,
        saveType: saveType,
        marketId: searchForm.marketId,
        markDate: searchForm.calendarDate,
      },
    });
  };

  const setTableData = (arr) => {
    if (arr instanceof Array) {
      const newArr = _.cloneDeep(arr);
      for (let i = 0; i < newArr.length; i++) {
        newArr[i].beginTime = timrArr.current[newArr[i].beginIndex];
        newArr[i].endTime = timrArr.current[newArr[i].endIndex];
      }

      const formData = arrToFormData(newArr, 'id', [
        'beginTime',
        'endTime',
        'rateValue',
        'dataSourceId',
        'useType',
        'maxValue',
        'minValue',
        'fixedValue',
      ]);
      onValuesChange(null, formData);
      form.setFieldsValue(formData);
    }
  };

  const changeOpenAi = (checked) => {
    if (checked) {
      return;
    }
    dispatch({
      type: 'shortTermForecastingRedesignV2/setState',
      payload: {
        openAi: 0,
      },
    });
    // 重置
    query({
      ...searchForm,
      reset: 0,
    });
  };

  // 启用ai策略
  const confirmEnableStrategy = () => {
    dispatch({
      type: 'shortTermForecastingRedesignV2/setState',
      payload: {
        openAi: 1,
      },
    });
    dispatch({
      type: 'shortTermForecastingRedesignV2/getAiTableData',
    });
  };

  const changeDataList = (index, type) => {
    const values = form.getFieldsValue();
    let newList = formDataToArr(values, dataList, 'id');
    if (type === 'delete') {
      if (newList.length === 1) {
        return message.warning('请至少保留一条数据');
      }
      Modal.confirm({
        title: '确定删除此行数据吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          newList.splice(index, 1);
          setDataList(newList);
          setTableData(newList);
        },
      });
    } else {
      newList.splice(index + 1, 0, {
        id: _.uniqueId('new'),
        useType: 'dataSource',
        fixedValue: '0.000',
        maxValue: defaultCapacity,
        minValue: '0.000',
        rateValue: 100,
        dataSourceId: dataSourceList?.[0]?.dataSourceId || null,
      });
      newList = newList.map((i) => (i.id ? i : { ...i, id: _.uniqueId(index), lineType: 'add' }));
      setDataList(newList);
      setTableData(newList);
    }
  };

  const changeUseType = (e, index) => {
    const value = e.target.value;
    const newList = [...dataList];
    newList[index].useType = value;
    setDataList(newList);
  };

  const changeSmoothStatus = (value) => {
    dispatch({
      type: 'shortTermForecastingRedesignV2/setState',
      payload: {
        smoothStatus: value,
      },
    });
  };

  const debounceFn = _.debounce((obj) => queryNewStrategy(obj), 2000);

  const onValuesChange = (changedValues, values) => {
    if (Object.values(values).every((i) => !!i)) {
      // 列表数据变化触发回掉，防抖处理2秒
      debounceFn(values);
    }
  };

  useEffect(() => {
    if (searchForm.marketId) {
      // 请求了页面右侧列表数据，获取到后在请求 功率预测及调整模拟 的数据
      query(searchForm);
    }
  }, [searchForm]);

  useEffect(() => {
    const formData = form.getFieldsValue();
    queryNewStrategy(formData);
  }, [store, smoothStatus, quoteStationId]);

  const changeLogVisible = () => {
    setLogVisible(!logVisible);
  };

  // 时间点输入鼠标移除时自动合并时段
  const onBlurCapture = () => {
    const obj = form.getFieldsValue();
    let arr = formDataToArr(obj, dataList, 'id');
    // 将数组中的时段字符串转换为timeIndex
    arr =
      arr?.map((i) => ({
        ...i,
        beginIndex:
          timrArr.current.indexOf(i.beginTime) === -1 ? null : timrArr.current.indexOf(i.beginTime),
        endIndex:
          timrArr.current.indexOf(i.endTime) === -1 ? null : timrArr.current.indexOf(i.endTime),
      })) || [];
    // 判断用户是否填写完毕
    if (arr.every((i) => i.beginIndex !== null && i.endIndex !== null)) {
      arr = buildContinuousTimePoint(arr);
      setDataList(arr);
      setTableData(arr);
    }
  };

  const saveTableData = async () => {
    const result = havePermissions('IteraShortTermForcastSaveButtton', buttonPermissions);
    if (result) {
      const obj = form.getFieldsValue();
      let arr = formDataToArr(obj, dataList, 'id');
      arr = arr.map((i) => ({
        ...i,
        timeSlot: i.beginTime + '-' + i.endTime,
      }));
      dispatch({
        type: 'shortTermForecastingRedesignV2/saveAdjustTableData',
        payload: {
          dataFrom: openAi ? 100 : 101, //（100, "-启用AI" \ 101, "-人工"）
          dataList: arr,
          markDate: searchForm.calendarDate,
          stationId: searchForm.stationId,
          smoothStatus: smoothStatus,
          marketId: searchForm.marketId,
          store: store,
          saveType: searchForm.saveType,
        },
      });
    }
  };

  const handleReSet = () => {
    query({
      ...searchForm,
      reset: 1,
    });
    dispatch({
      type: 'shortTermForecastingRedesignV2/setState',
      payload: {
        openAi: 0,
        quoteStationId: null,
      },
    });
  };

  // 打开策略引用弹窗
  const handleOpenStrategyModal = async () => {
    const result = await StrategyCitationModal.show({
      searchForm,
      menuCode,
    });
    if (result?.index === 1 && result.quoteStationId && result.dataList) {
      // 如果没有找到当前基准源则使用默认基准源
      const dataList =
        result?.dataList?.map((i) =>
          dataSourceList.some((d) => d.dataSourceId === i.dataSourceId)
            ? i
            : { ...i, dataSourceId: defaultDataSourceId },
        ) || [];
      dispatch({
        type: 'shortTermForecastingRedesignV2/setState',
        payload: {
          quoteStationId,
          dataList,
        },
      });
    }
  };

  return (
    <div className={styles.step_one_content}>
      <div className={styles.left}>
        <PriceSpreadCharts />
        <PowerPrediction />
      </div>

      <div className={styles.right}>
        <div className={styles.title}>
          <div className={styles.name}>
            调整策略编辑
            <Button type="link" onClick={changeLogVisible}>
              操作日志
            </Button>
          </div>
          <Space size={16} className={styles.btns}>
            <Button onClick={handleReSet}>重置</Button>
            <Button type="primary" onClick={saveTableData} disabled={saveButtonDisabled}>
              保存
            </Button>
          </Space>
        </div>

        <div className={styles.edit_options}>
          <div className={styles.item}>
            平滑：
            <Select
              suffixIcon={<CaretDownOutlined />}
              bordered={false}
              value={smoothStatus}
              onChange={changeSmoothStatus}
              options={smoothOptions}
            />
          </div>
          {/* 甘肃山东没有AI启用策略 */}
          {searchForm && searchForm.marketId !== 'PHBSD' && searchForm.marketId !== 'PXBGS' && (
            <div className={styles.item}>
              <Button type="link" icon={<ApartmentOutlined />} onClick={handleOpenStrategyModal}>
                策略引用
              </Button>
              <Divider type="vertical" />
              <Popconfirm
                title="注意: 启用AI将覆盖人工调整策略!"
                onConfirm={confirmEnableStrategy}
                okText="确认"
                cancelText="取消"
                disabled={!!openAi}
              >
                <Switch checked={!!openAi} onChange={changeOpenAi} />
              </Popconfirm>
              启用AI策略
            </div>
          )}
        </div>

        <div className={styles.edit_table}>
          <Spin spinning={dataListLoading}>
            <Form onValuesChange={onValuesChange} form={form}>
              <TjTable
                columns={getColumns({
                  dataSourceList,
                  changeUseType,
                  changeDataList,
                  onBlurCapture,
                })}
                dataSource={dataList}
              />
            </Form>
          </Spin>
        </div>

        <div className={styles.chart_box}>
          {aiAdjustmentLoading ? (
            <Spin spinning={true} />
          ) : Object.keys(aiAdjustmentChartData).length > 0 ? (
            <TjChart option={aiAdjustmentChartData} group={'C'} />
          ) : (
            <TRDefault type={'emptysm'} message={'暂无数据'} />
          )}
        </div>
      </div>

      <LogModal visible={logVisible} onCancel={changeLogVisible} type={2} />
    </div>
  );
};

export default connect(({ shortTermForecastingRedesignV2, global }) => ({
  searchForm: shortTermForecastingRedesignV2.searchForm,
  dataList: shortTermForecastingRedesignV2.dataList,
  smoothStatus: shortTermForecastingRedesignV2.smoothStatus,
  quoteStationId: shortTermForecastingRedesignV2.quoteStationId,
  store: shortTermForecastingRedesignV2.store,
  dataSourceList: shortTermForecastingRedesignV2.dataSourceList,
  openAi: shortTermForecastingRedesignV2.openAi,
  menuCode: global.configure.menuCode,
  dataListLoading: shortTermForecastingRedesignV2.dataListLoading,
  saveType: shortTermForecastingRedesignV2.saveType,
  aiAdjustmentLoading: shortTermForecastingRedesignV2.aiAdjustmentLoading,
  aiAdjustmentChartData: shortTermForecastingRedesignV2.aiAdjustmentChartData,
  saveButtonDisabled: shortTermForecastingRedesignV2.saveButtonDisabled,
  buttonPermissions: global.configure.buttonPermissions,
  defaultDataSourceId: shortTermForecastingRedesignV2.defaultDataSourceId,
  defaultCapacity: shortTermForecastingRedesignV2.defaultCapacity,
}))(StepOneContent);
